package com.budwk.app.sqfw.component;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.ocr_general.HttpUtil;
import com.budwk.app.sqfw.vo.HonorAppVo;
import com.budwk.app.util.StrUtil;
import com.budwk.starter.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.nutz.http.Header;
import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.net.http.HttpClient;
import java.util.HashMap;
import java.util.Map;

/**
 * 荣耀app相关接口实现服务类
 */

@IocBean
@Slf4j
public class HonorAppComponent {

    @Inject
    private RedisService redisService;

    private static final String WK_MINI_HONOR_APP_ACCESS_TOKEN = "wk_mini_honor_app_access_token"; // 荣耀app的缓存token key值

    private static final String APP_PUBLISH_URL = "https://appmarket-openapi-drcn.cloud.hihonor.com";

    private static final String APP_PUBLISH_ACCESS_URL = "https://iam.developer.hihonor.com";

    // app id  104431708
    public Result<?> queryDetail() {
        String accessToken = getAccessToken();
        HonorAppVo appVo = HonorAppVo.init();
        // 入参
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appId", appVo.getAppId());
        // 请求头
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        String url = String.format("%s%s", APP_PUBLISH_URL, "/openapi/v1/publish/get-app-detail");
        JSONObject resJson = HttpUtil.sendGet(url, paramsMap, headerMap);
        log.info("HonorAppComponent queryDetail res: {}", JSONObject.toJSONString(resJson));
        if (resJson == null) {
            return Result.error();
        }
        Integer code = resJson.getInteger("code");
        if (code == null || code != 0) {
            return Result.error(resJson.getString("msg"));
        }
        JSONObject dataJson = resJson.getJSONObject("data");
        return Result.data(dataJson.getJSONObject("releaseInfo"));
    }

    private String getAccessToken() {
        // 1 从redis中获取
        String versionData = redisService.get(WK_MINI_HONOR_APP_ACCESS_TOKEN);
        if (StringUtils.isNotEmpty(versionData)) {
            return versionData;
        }
        // 2 远程查询接口获取
        String token = getHttpAccessToken();
        // 存入redis缓存 10分钟
        redisService.setex(WK_MINI_HONOR_APP_ACCESS_TOKEN, 600, token);
        return token;
    }

    // 调用远程接口获取token
    private String getHttpAccessToken() {
        HonorAppVo appVo = HonorAppVo.init();
        log.info("http post queryHonorAppDetail start");
        // 请求参数
        Map<String, Object> parms = new HashMap<>();
        parms.put("grant_type", appVo.getGrantType());
        parms.put("client_id", appVo.getClientId());
        parms.put("client_secret", appVo.getClientSecret());
        String url = String.format("%s%s", APP_PUBLISH_ACCESS_URL, "/auth/token");
        String response = Http.post(url,parms,5 * 1000); // 可以同时设置超时时间
        log.info("http post queryHonorAppDetail end");
        if (StringUtils.isEmpty(response)) {
            log.info("http post queryHonorAppDetail response is null res: {}", response);
            throw new AppException("接口异常，未查询到任何数据");
        }
        JSONObject resJson = JSONObject.parseObject(response);
        String accessToken = resJson.getString("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            log.info("http post queryHonorAppDetail end res: {}", response);
            throw new AppException("获取token为空，请检查");
        }
        return accessToken;
    }
}
